const request = require('../../../../../utils/request')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isFocus: false,
        inputValue: '',
        currentTag: 0,
        historyList: [],
        hotSearch: [],


        tabList: [{
                name: '综合',
            },
            {
                name: '销量',
                checked: false,
                asc: false,
                nocheck: true
            },
            {
                name: '价格',
                checked: false,
                asc: false,
                nocheck: true
            }
        ],

        keyWord: '',

        sales: '',
        price: '',

        list: [],
        lastPage: false, //是否是最后一页
        page: 1,
        // 搜索历史
        historyArr: [],
        saveArr: [], //保存历史列表
        history: [], //显示历史列表

        isClear: false,
    },
    onLoad() {

      
    },
    onShow() {
      let history = wx.getStorageSync('history') ? wx.getStorageSync('history') : null;
      if (history) {
          history.forEach(function (obj, index) {
              if (!obj) {
                  _this.history.splice(index, 1);
              }
          });
          this.setData({
              history
          })
      }
      this.setData({
        list: [],
        lastPage: false, //是否是最后一页
        page: 1,
      })
      this.getHistory()
      this.getList()
      if (wx.getStorageSync('token')) {
        getApp().getCartNum()
      }
    },
    initData() {
        let tabList = this.data.tabList
        tabList.forEach(function (obj, index) {
            obj.checked = false
            obj.asc = false
            obj.nocheck = true
        })
        this.setData({
            list: [],
            page: 1,
            sales: '',
            price: '',
            tabList,
            currentTag: 0,
            isFocus: false
        })
    },
    inputWrite(e) {
        this.setData({
            keyWord:e.detail.value
        })
    },
    add(e) {
      let list = this.data.list
      let item = e.detail.item ? e.detail.item : e.currentTarget.dataset.item
      let index = e.detail.index ? e.detail.index : e.currentTarget.dataset.index || 0
      if (!item.addSwitch) {
        item.addSwitch = true
        item.cart_num++
      }
      this.addCartApi(item,index)
      // list[index] = item
      if(list[index].product_id == item.id){
        list[index].cart_num = item.cart_num
        list[index].addSwitch = item.addSwitch
      }
      this.setData({
        list
      })
    },
    // 购物车加减
    addCartReduce(e) {
      let type = e.detail.type ? e.detail.type : e.currentTarget.dataset.type //1 减 2 加
      let item = e.detail.item ? e.detail.item : e.currentTarget.dataset.item
      let index = e.detail.index ? e.detail.index : e.currentTarget.dataset.index || 0
      let list = this.data.list
      if (type == 1) {
        if (item.cart_num == 0) {
          // getApp().toast('商品不能再减了~')
          return
        }
        item.cart_num--
      } else {
        item.cart_num++
      }
  
      this.addCartApi(item, index)
      list[index] = Object.assign(list[index], item)
      this.setData({
        list
      })
  
    },
    addCartApi(item, index) {
      let list = this.data.list
      request._post('/api?method=cart.add', {
        product_id: item.product_id || item.id,
        nums: item.cart_num,
        num_type: 2,
      }, 'noload').then(res => {
        getApp().getCartNum()
        getApp().globalData.changePoint = true
        if(item.cart_num == 0){
          list[index].addSwitch = false
          this.setData({
            [`list[${index}]`]: list[index]
          })
        }
      }).catch(res => {
        // 库存不足情况--
        list[index].cart_num--
        if( list[index].cart_num == 0) {
          list[index].addSwitch =false
        }
        this.setData({
          [`list[${index}]`]: list[index]
        })
      })
    },
    // 关键词搜索
    searchInput() {
        let history = this.data.history
        let keyWord = this.data.keyWord
        if (!this.data.keyWord) {
            // wx.showToast({
            //     title: '请输入关键词',
            //     icon: 'none'
            // })
            return;
        }
        if (!history) {
            history = []
        }
        if (history.length > 0) {
            // 有数据的话 判断
            if (history.indexOf(this.data.keyWord) !== -1) {
                // 有相同的，先删除 再添加
                history.splice(history.indexOf(keyWord), 1);
                history.unshift(keyWord);
            } else {
                history.unshift(keyWord); // 没有相同的 添加
            }
        } else {
            // 没有数据 添加
            history.unshift(keyWord);
        }
        if (history.length > 6) {
            // 保留六个值
            history.pop();
        }
        this.setData({
            history,
        })
        wx.setStorage({
            key: 'historyList',
            data: history,
        })
        wx.setStorage({
            key: 'history',
            data: history,
        })
        this.initData()
        this.getList()
    },
    // 选择价格销量
    clickTag(e) {
        let _this = this
        let index = e.currentTarget.dataset.index
        let tabList = this.data.tabList
        tabList[index].checked = !tabList[index].checked
        tabList.forEach(function (obj, i) {
            if (i != index) {
                obj.checked = false
                obj.asc = false
                obj.nocheck = true

            } else {
                obj.asc = !obj.asc
                obj.nocheck = false
                // 赋值desc asc
                if (index == 1) {
                    if (obj.asc) {
                        _this.setData({
                            sales: 'desc'
                        })
                    } else {
                        _this.setData({
                            sales: 'asc'
                        })
                    }
                }

                if (index == 2) {
                    if (obj.asc) {
                        _this.setData({
                            price: 'desc'
                        })
                    } else {
                        _this.setData({
                            price: 'asc'
                        })
                    }
                }
            }
        })
        this.setData({
            tabList,
            currentTag: index,
            list: [],
            page: 1
        })

        this.getList()

    },
    // 点击热门搜索
    hotKeyClick(e) {
        this.setData({
            keyWord: e.currentTarget.dataset.item,
            isClear: true
        })
    },
    /**
     * 获取焦点
     */
    inputFocus: function () {
        this.setData({
            isFocus: true
        });
    },
    /**
     * 获取焦点
     */
    inputBlur: function () {
        this.setData({
            // isFocus: false
        });
    },
    /**
     * 取消 清除input内容
     */
    clearInput: function () {
        this.initData()
        this.setData({
            isFocus: false,
            keyWord: '',
            isClear: false,
            inputShowed: false,
            page:1,
            list:[]
        })
        this.getList()
    },
    // 清空输入框
    clearData() {
        this.setData({
            keyWord: '',
            isClear: false,
            isFocus: false,
            inputShowed: false,
            list:[],
            page:1
        })
        if(this.data.isFocus) {
            return
        }
       
        this.getList()
    },
    delHis() {
        this.setData({
            history: null
        })
        wx.removeStorage({
            key: 'history',
        })
    },
    /**
     * 输入
     */
    inputChange: function (e) {
        this.setData({
            keyWord: e.detail.value,
            isClear: true
        })
        if (!e.detail.value) {
            this.setData({
                isClear: false
            })
        }
    },

    // 获取搜索历史
    getHistory() {
        let _this = this
        request._post('/api?method=merchants.goodsSearch', {}).then(res => {
            _this.setData({
                hotSearch: res.data.keyword,
                historyList: res.data.info
            })
        })
    },
    // 初始化输入框
    initHis() {
        this.history = localStorage.getItem("historyList") ?
            JSON.parse(localStorage.getItem("historyList")) :
            null;
        if (this.history) {
            this.history.forEach(function (obj, index) {
                if (!obj) {
                    _this.history.splice(index, 1);
                }
            });
        }
    },
    // 获取热词
    getList() {
        let _this = this
        let location_id = wx.getStorageSync('localXiaoqu') ? wx.getStorageSync('localXiaoqu').id:''
        request._post('/api?method=merchants.goodsList', {
            key: this.data.keyWord,
            sales: this.data.sales,
            price: this.data.price,
            page: this.data.page,
            xiaoqu:location_id
        }).then(res => {
            if (res.data) {
                if (res.data.length == 0) {
                    _this.setData({
                        lastPage: true
                    })
                    return
                } else {
                    _this.setData({
                        lastPage: false
                    })
                }

                _this.setData({
                    list: _this.data.list.concat(res.data),
                })
                _this.dealList()
            }
        })
    },
    dealList() {
      let list = this.data.list
      list.forEach(function (obj, index) {
        obj.addSwitch = false
        if (obj.cart_num) {
          obj.addSwitch = true
        }
      })
      this.setData({
        list
      })
    },
    toDetail(e) {
        let id = e.currentTarget.dataset.item.id
        wx.navigateTo({
            url: '/pages/home/pages/my/product-details/product-details?id=' + id,
        })
    },
    onReachBottom: function () {
        if (this.data.lastPage) {
            return
        }
        let page = this.data.page
        page++
        this.setData({
            page
        })
        this.getList()
    },


})